package in.muton.edushare.mailer;

import java.util.Date;

import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.quartz.impl.StdSchedulerFactory;

public class MailMonitor implements JobListener {
	Scheduler sched = null;
	JobDetail jobDetail;	
	SimpleTrigger trigger;
	public String getName() {
		return "Mailsender listener";
	}

	public void jobExecutionVetoed(JobExecutionContext arg0) {
	}

	public void jobToBeExecuted(JobExecutionContext arg0) {
	}

	public void jobWasExecuted(JobExecutionContext arg0,
			JobExecutionException arg1) {
		long startTime = System.currentTimeMillis() + 30000L;

		if(jobDetail == null)
			jobDetail = new JobDetail("myJob",null, MailThread.class);
		
		if(sched != null){
			try {
				sched.unscheduleJob("myTrigger", null);
			} catch (SchedulerException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		trigger = new SimpleTrigger("myTrigger",
		            null,new Date(startTime),null, 0, 0L);

		try {			
			if(sched==null){
				SchedulerFactory schedFact = new StdSchedulerFactory();
				try {
					sched = schedFact.getScheduler();
					sched.start();
					sched.addGlobalJobListener(this);
				} catch (SchedulerException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			sched.scheduleJob(jobDetail,trigger);
		} catch (SchedulerException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
